<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 Tangchao All rights reserved.
// +----------------------------------------------------------------------
// | Author: xiaoying <360963804@qq.com>
// +----------------------------------------------------------------------
namespace plugins\wx_login\controller;

use cmf\controller\PluginBaseController;
use think\Db;
// use app\user\model\UserModel;
// use think\Exception;

class IndexController extends PluginBaseController
{
    //pc扫码登录
    function qrcode()
    {
        $redirect_uri = cmf_get_plugin_config('WxLogin')['callback'];
        $redirect_uri = urlencode($redirect_uri); //该回调需要url编码
        $appID = cmf_get_plugin_config('WxLogin')['AppID'];
        $scope = "snsapi_login";
        //准备向微信发请求
        $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID . "&redirect_uri=" . $redirect_uri
            . "&response_type=code&scope=" . $scope . "&state=STATE#wechat_redirect";
        header("Location:$url");
    }


    //微信公众号登录
    function h5()
    {
        $redirect_uri = cmf_get_plugin_config('WxLogin')['callback'];
        $redirect_uri = urlencode($redirect_uri); //该回调需要url编码
        $appID = cmf_get_plugin_config('WxLogin')['AppID'];
        $scope = "snsapi_userinfo";
        //snsapi_userinfo  snsapi_base  snsapi_login
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appID&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=STATE#wechat_redirect";
        $this->redirect($url);
    }


    //wx回调函数
    // array(10) {
    //     ["openid"] => string(28) "XXXXXX"
    //     ["nickname"] => string(3) "XXXXX"
    //     ["sex"] => int(1)
    //     ["language"] => string(5) "zh_CN"
    //     ["city"] => string(0) ""
    //     ["province"] => string(9) "Abu Dhabi"
    //     ["country"] => string(2) "AE"
    //     ["headimgurl"] => string(130) "XXXXX"
    //     ["privilege"] => array(0) {
    //     }
    //     ["unionid"] => string(28) "XXXXXX"
    //   }
    function callback()
    {
        $code = $_GET["code"];
        $appid = cmf_get_plugin_config('WxLogin')['AppID'];
        $secret = cmf_get_plugin_config('WxLogin')['AppSecret'];
        if (!empty($code))  //有code
        {
            //通过code获得 access_token + openid
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid
                . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
            $jsonResult = file_get_contents($url);
            $resultArray = json_decode($jsonResult, true);

            $accesstoken = $resultArray["access_token"];
            $openid = $resultArray["openid"];

            cookie('accesstoken', $accesstoken, 24 * 60 * 60 * 7);
            cookie('openid', $openid, 24 * 60 * 60 * 7);

            //通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里,后面再写自己的代码逻辑
            $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $accesstoken . "&openid=" . $openid;
            $infoResult = file_get_contents($infoUrl);

            //用户信息
            $userinfo = json_decode($infoResult, true);
            $sex = $userinfo["sex"];

            //print_r($userinfo);
            //在third_party_user表中查找是否已经存在此用户
            $openidfind = db("third_party_user")->where("openid", $openid)->find();


            //判断此时用户是否已经登录	
            $user_id = cmf_get_current_user_id();
            if ($user_id) {
                //用户已经登录，表示用户要绑定wx
                if ($openidfind) {
                    //third_party_user表中 已经存在此用户 表明此WX已经绑定其他账户
                    $this->error('此WX已经绑定其他账户,请换WXQ账号重试', url('user/profile/binding'));
                } else {
                    //此WX可正常绑定
                    //更新user表用户信息
                    $userdata = [
                        "last_login_ip"   => get_client_ip(0, false),
                        "last_login_time" => time(),
                        "sex"             => $sex,
                        "user_nickname"   => $userinfo["nickname"],
                        "avatar"          => $userinfo["headimgurl"],
                        // "signature"       => $userinfo["msg"],
                    ];
                    $userdatares = db("user")->where("id", $user_id)->update($userdata);

                    $thirddata = [
                        "access_token"    => $accesstoken,
                        "nickname"        => $userinfo["nickname"],
                        "last_login_time" => $userdata["last_login_time"],
                        "expire_time"     => $userdata["last_login_time"] + 24 * 60 * 60 * 7,
                        "last_login_ip"   => $userdata["last_login_ip"],
                        "create_time"     => time(),
                        "openid"          => $openid,
                        "user_id"         => $user_id,
                        "third_party"     => "WX",
                        "login_times"     => 1,
                        "more"            => json_encode($userinfo, JSON_UNESCAPED_UNICODE)
                    ];
                    $thirddatares = db("third_party_user")->insert($thirddata);
                    $this->error('成功绑定微信', url('user/profile/binding'));
                }
            }


            if ($openidfind) { //third_party_user表中 已经存在此用户
                $thirddata = [
                    "access_token"    => $accesstoken,
                    "nickname"        => $userinfo["nickname"],
                    "login_times"     => $openidfind["login_times"] + 1,
                    "last_login_time" => time(),
                    "expire_time"     => time() + 24 * 60 * 60 * 7,
                    "last_login_ip"   => get_client_ip(0, false),
                    "third_party"     => "WX",
                    "more"            => json_encode($userinfo, JSON_UNESCAPED_UNICODE)
                ];
                $userdata = [
                    "last_login_ip"   => $thirddata["last_login_ip"],
                    "last_login_time" => $thirddata["last_login_time"],
                ];
                $thirddatares = db("third_party_user")->where("openid", $openid)->update($thirddata);
                $userdatares = db("user")->where("id", $openidfind["user_id"])->update($userdata);
                $userid = $openidfind["user_id"];
            } else {
                //third_party_user表中 无此用户
                $userdata = [
                    "last_login_ip"   => get_client_ip(0, false),
                    "last_login_time" => time(),
                    "create_time"     => time(),
                    "sex"             => $sex,
                    "user_nickname"   => $userinfo["nickname"],
                    "avatar"          => $userinfo["headimgurl"],
                    // "signature"       => $userinfo["msg"],
                ];
                $userdatares = db("user")->insertGetId($userdata);
                $thirddata = [
                    "access_token"    => $accesstoken,
                    "nickname"        => $userinfo["nickname"],
                    "last_login_time" => $userdata["last_login_time"],
                    "expire_time"     => $userdata["last_login_time"] + 24 * 60 * 60 * 7,
                    "last_login_ip"   => $userdata["last_login_ip"],
                    "create_time"     => $userdata["create_time"],
                    "openid"          => $openid,
                    "user_id"         => $userdatares,
                    "third_party"     => "WX",
                    "login_times"     => 1,
                    "more"            => json_encode($userinfo, JSON_UNESCAPED_UNICODE)
                ];
                $thirddatares = db("third_party_user")->insert($thirddata);
                $userid = $userdatares;
            }

            //此时已经获取user表中的用户id

            $res = db("user")->where("id", $userid)->find();
            session('user', $res);
            $token = cmf_generate_user_token($res["id"], 'web');
            if (!empty($token)) {
                session('token', $token);
            }
            $session_login_http_referer = session('login_http_referer');
            $redirect                   = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            $log = 0;
            //拉黑判断。
            if ($res['user_status'] == 0) {
                $log = 3;
            }
            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $this->redirect($redirect);
                    break;
                case 1:
                    $this->error(lang('PASSWORD_NOT_RIGHT'));
                    break;
                case 2:
                    $this->error('账户不存在');
                    break;
                case 3:
                    $this->error('账号被禁止访问系统');
                    break;
                default:
                    $this->error('未受理的请求');
            }
        }
    }
}
